const logger = require('../utils/logger');

// 存储请求的防抖状态
const requestCache = new Map();

/**
 * 防抖中间件
 * @param {number} wait 等待时间（毫秒）
 * @param {string} key 防抖键值，用于标识请求
 * @returns {Function} 中间件函数
 */
const debounceMiddleware = (wait = 1000, key = 'default') => {
  return (req, res, next) => {
    // 生成请求的唯一标识
    const requestKey = `${key}_${req.method}_${req.originalUrl}_${JSON.stringify(req.body)}_${req.user?.id || 'anonymous'}`;
    
    // 检查是否在防抖期内
    const now = Date.now();
    const cached = requestCache.get(requestKey);
    
    if (cached && (now - cached.timestamp) < wait) {
      logger.warn(`防抖拦截重复请求: ${requestKey}`);
      return res.status(429).json({
        code: 429,
        message: '请求过于频繁，请稍后再试',
        data: null
      });
    }
    
    // 记录当前请求
    requestCache.set(requestKey, {
      timestamp: now
    });
    
    // 清理过期的缓存（超过5分钟）
    const cleanupTime = 5 * 60 * 1000; // 5分钟
    for (const [cacheKey, cacheValue] of requestCache.entries()) {
      if (now - cacheValue.timestamp > cleanupTime) {
        requestCache.delete(cacheKey);
      }
    }
    
    next();
  };
};

/**
 * 为特定路由创建防抖中间件
 * @param {number} wait 等待时间（毫秒）
 * @returns {Function} 中间件函数
 */
const createDebounceMiddleware = (wait = 1000) => {
  return (req, res, next) => {
    const key = `${req.method}_${req.originalUrl}`;
    return debounceMiddleware(wait, key)(req, res, next);
  };
};

module.exports = {
  debounceMiddleware,
  createDebounceMiddleware
}; 